package com.example.mygaode.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.overlay.PoiOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.example.mygaode.R;
import com.example.mygaode.lib.LocationTask;
import com.example.mygaode.lib.OnLocationGetListener;
import com.example.mygaode.lib.PoiSearchTask;
import com.example.mygaode.lib.PositionEntity;
import com.example.mygaode.lib.RecomandAdapter;
import com.example.mygaode.lib.RegeocodeTask;
import com.example.mygaode.lib.RouteTask;
import com.example.mygaode.route.DrivingRouteOverLay;
import com.example.mygaode.utils.AMapUtil;
import com.example.mygaode.utils.ToastUtil;
import com.example.mygaode.utils.Utils;
import com.example.mylibrarybase.utils.LogUtils;
import com.example.mylibrarybase.utils.UtilsToast;

import java.util.ArrayList;
import java.util.List;

import static com.example.mygaode.R.id.map;


public class Main2Activity_ditu extends AppCompatActivity implements LocationSource, AMapLocationListener,
        AMap.OnMapClickListener, AMap.OnMarkerClickListener,
        AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter,
        RouteSearch.OnRouteSearchListener ,TextWatcher,
        AdapterView.OnItemClickListener ,OnLocationGetListener,
        AMap.OnMapLoadedListener,RouteTask.OnRouteCalculateListener
        {

    private MapView mMapView;
    private AMap mAMap;
    private TextView mStart_locsh;
    private AMapLocationClient locationClient;
    private TextView stop_locsh;
    private AMapLocationClientOption locationOption = new AMapLocationClientOption();
    private UiSettings mUiSettings;
   // private AMapLocationClientOption LocationOption;

    //我的位置的 经纬度
    private double mLongitude;

    private double mLatitude;

    private LatLonPoint lp = new LatLonPoint(mLongitude, mLatitude);//
    private EditText mEd_sousuo;
    private String keyWord = "";// 要输入的poi搜索关键字
    private ProgressDialog progDialog = null;// 搜索时进度条
    private EditText editCity;// 要输入的城市名字或者城市区号
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private TextView tv_sousuo;
    private boolean tagg;
    private float mMaxZoomLevel;
    private float mMinZoomLevel;
    //驾车路线规划
    private final int ROUTE_TYPE_DRIVE = 2;
    //路线规划 起点
    private LatLonPoint mStartPoint ;//起点，116.335891,39.942295
    //路线规划 终点
    private LatLonPoint mEndPoint ;//终点，116.481288,39.995576
    private RouteSearch mRouteSearch;
    private DriveRouteResult mDriveRouteResult;
    private EditText ed_start;
    private EditText ed_end;
    private GeocodeSearch geocoderSearch;
    //终点文字信息
    private String addressName;
    //选择的点
    private LatLonPoint mLatLonPoint;

    private Marker regeoMarker;
    private TextView tv_loacatme;
    private TextView tv_guihua;
    private TextView tv_cler;
    private RecomandAdapter mRecomandAdapter;

    //联想搜索框的listView
    private ListView mRecommendList;
    private RouteTask mRouteTask;
    //结果集
    private List<PoiItem> mPoiItems;
    private LatLng mStartPosition;
    private LocationTask mLocationTask;
    private Marker mPositionMark;
            private RegeocodeTask mRegeocodeTask;

            @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2_ditu);

        //获取地图控件引用
        mMapView = (MapView) findViewById(map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        //初始化地图变量 单例模式
        if (mAMap == null) {

            mAMap = mMapView.getMap();
            //地图上的UI控件的控制器
            mUiSettings = mAMap.getUiSettings();

            regeoMarker = mAMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory
                            .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
        }
        //注册监听
        registerListener();
        //初始化页面上的view 包括高德地图
        initView();
        //初始化定位
        initLocation();
        //初始化搜索框的集合
        initAdapter();
        //简单定位
        mLocationTask = LocationTask.getInstance(getApplicationContext());
        mLocationTask.setOnLocationGetListener(this);
        mRegeocodeTask = new RegeocodeTask(getApplicationContext());
        RouteTask.getInstance(getApplicationContext())
                .addRouteCalculateListener(this);

//        if (AMapUtil.isAllowMockLocation(this, new DialogUtils.callback() {
//            @Override
//            public void confirm(String selectorButton, String which, int status, int position) {
//              startActivity(new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS));
//                finish();
//               // return;
//            }
//
//            @Override
//            public void cancel() {
//                finish();
//               // return;
//            }
//
//            @Override
//            public void dismiss() {
//                finish();
//                //return;
//            }
//        })){
//            //finish();
//           // return;
//        }
    }
    @Override
    public void onMapLoaded() {

//        MarkerOptions markerOptions = new MarkerOptions();
//        // markerOptions.setFlat(true);
//        markerOptions.anchor(0.5f, 0.5f);
//        markerOptions.position(new LatLng(0, 0));
//        markerOptions
//                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
//                        .decodeResource(getResources(),
//                                R.drawable.icon_loation_start)));
//        mPositionMark = mAMap.addMarker(markerOptions);
//
//        mPositionMark.setPositionByPixels(mMapView.getWidth() / 2,
//                mMapView.getHeight() / 2);
        mLocationTask.startSingleLocate();
    }
    private void initAdapter() {
        mRouteTask =RouteTask.getInstance(getApplicationContext());

        mRecomandAdapter =new RecomandAdapter(getApplicationContext());
        mRecommendList.setAdapter(mRecomandAdapter);
        mRecommendList.setOnItemClickListener(this);
    }

    /**
     * 注册监听
     */
    private void registerListener() {
        mAMap.setOnMapClickListener(this);
        mAMap.setOnMarkerClickListener(this);
        mAMap.setOnInfoWindowClickListener(this);
        mAMap.setInfoWindowAdapter(this);

    }

    /**
     * 初始化地图上的view
     */
    private void initView() {
         mRecommendList = (ListView) findViewById(R.id.recommend_list);

        mEd_sousuo = (EditText) findViewById(R.id.ed_sousuo);
        //mEd_sousuo.addTextChangedListener(this);

        ed_start = (EditText) findViewById(R.id.ed_start);
        ed_end = (EditText) findViewById(R.id.ed_end);

        tv_sousuo = (TextView) findViewById(R.id.tv_sousuo);
        tv_cler = (TextView) findViewById(R.id.tv_cler);
        tv_guihua = (TextView) findViewById(R.id.tv_guihua);
        tv_loacatme = (TextView) findViewById(R.id.tv_loacatme);
        mStart_locsh = (TextView) findViewById(R.id.start_locsh);
        stop_locsh = (TextView) findViewById(R.id.stop_locsh);
        mStart_locsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // startLocation();
                //开启跟随
                if (!tagg){
                    tagg = true;
                    mStart_locsh.setText("取消跟随");
                }else{
                    tagg =false;
                    mStart_locsh.setText("开启跟随");
                }
            }
        });
        //停止定位被点击了
        stop_locsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopLocation();
            }
        });
        //搜索被点击了
        tv_sousuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = mEd_sousuo.getText().toString();
                //搜索poi
                doSearchQuery(s,"","230100");

                Intent intent = new Intent(Main2Activity_ditu.this, DestinationActivity.class);
                intent.putExtra("sousuo",s);
                startActivityForResult(intent,0);
               // PoiSearchTask poiSearchTask=new PoiSearchTask(getApplicationContext(), mRecomandAdapter);


               // poiSearchTask.search(mEd_sousuo.getText().toString(),RouteTask.getInstance(getApplicationContext()).getStartPoint().city);
            }
        });
        //当前位置被点击了
        tv_loacatme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ed_start.setText("当前位置");
            }
        });
        //点击了规划
        tv_guihua.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //开始规划
                searchRouteResult(ROUTE_TYPE_DRIVE, RouteSearch.DrivingDefault);

            }
        });

        tv_cler.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点击了清除
                mAMap.clear();
            }
        });

    }

    /**
     * 返回码
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 0:
//                PositionEntity result = (PositionEntity) data.getSerializableExtra("result");
//                if (null!=result){
//                    //搜索poi
//                    doSearchQuery(result.address,"","230100");
//                    mAMap.animateCamera(CameraUpdateFactory.changeLatLng(new LatLng(
//                            result.latitue,result.longitude)));
//                }

                break;
            case 1:
//                String sou = data.getStringExtra("sou");
//                if (null!=sou){
//                    //搜索poi
//                  //  doSearchQuery(result.address,"","230100");
////                    mAMap.animateCamera(CameraUpdateFactory.changeLatLng(new LatLng(
////                            result.latitue,result.longitude)));
//                    mEd_sousuo.setText(sou);
//                    mEd_sousuo.setSelection(mEd_sousuo.length());
  //              }

                break;
        }
//        switch (resultCode){
//            case :
//
//            break;
//        }
    }

    /**
     * 初始化定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void initLocation(){
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
        // 设置定位监听
        mAMap.setLocationSource(this);
        // 是否显示默认的定位按钮
        mUiSettings.setMyLocationButtonEnabled(true);
        // 是否可触发定位并显示定位层
        mAMap.setMyLocationEnabled(true);
        //获取最大级别
        mMaxZoomLevel = mAMap.getMaxZoomLevel();
        //获取最小级别
        mMinZoomLevel = mAMap.getMinZoomLevel();
        LogUtils.i("缩放级别"+"maxZoomLevel"+ mMaxZoomLevel +"\n"+"minZoomLevel"+ mMinZoomLevel);
        //设定初始化缩放级别
        mAMap.moveCamera(CameraUpdateFactory.zoomTo(mMaxZoomLevel -4));
       // mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lp.getLatitude(), lp.getLongitude()), 20));
        //路径规划
        mRouteSearch = new RouteSearch(this);
        //路径规划 回调
        mRouteSearch.setRouteSearchListener(this);
    }
    /**
     * 开始定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void startLocation(){
        //根据控件的选择，重新设置定位参数
       // resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
       // 启动定位
        locationClient.startLocation();



    }
    //第一次定位用到的监听
    LocationSource.OnLocationChangedListener mListener;
    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loc) {
            if (null != loc) {
                mLongitude = loc.getLongitude();
                mLatitude = loc.getLatitude();

                //解析定位结果
                String result = Utils.getLocationStr(loc);
                LogUtils.i("现在定位位置"+result);
                mListener.onLocationChanged(loc);// 显示系统小蓝点
                //tvReult.setText(result);
                //mAMap.animateCamera(CameraUpdateFactory.);
                if (tagg){
                    //移动到某个坐标
                    mAMap.animateCamera(CameraUpdateFactory.changeLatLng(new LatLng(
                            mLatitude,mLongitude)));
                    //移动到某个做表 并且设置 缩放级别
                   // mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng( mLatitude,mLongitude),mMaxZoomLevel -4));
                }
                } else {
               // tvReult.setText("定位失败，loc is null");
                UtilsToast.showToast(Main2Activity_ditu.this,"定位失败，loc is null" );
            }
        }
    };
    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void stopLocation(){
        // 停止定位
        locationClient.stopLocation();

    }
    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        LogUtils.i("默认的定位参数");
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(5000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是ture
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        return mOption;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        stopLocation();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
        startLocation();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
        //stopLocation();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (locationClient == null) {
            locationClient = new AMapLocationClient(this);
            locationOption = new AMapLocationClientOption();
            //设置定位监听
            locationClient.setLocationListener(this);
            //设置为高精度定位模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            locationClient.setLocationOption(locationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            locationClient.startLocation();
        }
    }
    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在搜索:\n" + keyWord);
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    /**
     * 范围搜索 以什么点进行附近搜索
     * @param keyWord
     * @param poi
     * @param city
     */
    public void doSearchQuery(String keyWord,String poi,String city) {
        currentPage = 0;
        query = new PoiSearch.Query(keyWord, poi, city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        query.requireSubPois(true);//true 搜索结果包含POI父子关系; false

        lp = new LatLonPoint(mLongitude, mLatitude);//
        if (lp != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                /**
                 * POI信息查询回调方法
                 */
                @Override
                public void onPoiSearched(PoiResult result, int rCode) {
                    dissmissProgressDialog();// 隐藏对话框
                    if (rCode == 1000) {
                        if (result != null && result.getQuery() != null) {// 搜索poi的结果
                            if (result.getQuery().equals(query)) {// 是否是同一条
                                poiResult = result;
                                // 取得搜索到的poiitems有多少页
                                // 取得第一页的poiitem数据，页数从数字0开始
                                mPoiItems = poiResult.getPois();
                                List<SuggestionCity> suggestionCities = poiResult
                                        .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                                LogUtils.i("结果集集合"+ mPoiItems);
                                if (mPoiItems != null && mPoiItems.size() > 0) {
                                    mAMap.clear();// 清理之前的图标
                                    PoiOverlay poiOverlay = new PoiOverlay(mAMap, mPoiItems);
                                    poiOverlay.removeFromMap();
                                    poiOverlay.addToMap();
                                    poiOverlay.zoomToSpan();
                                } else if (suggestionCities != null
                                        && suggestionCities.size() > 0) {
                                    showSuggestCity(suggestionCities);
                                } else {
                                    UtilsToast.showToast(Main2Activity_ditu.this,
                                            "对不起，没有搜索到相关数据");
                                }
                            }
                        } else {
                            UtilsToast.showToast(Main2Activity_ditu.this,
                                    "对不起，没有搜索到相关数据");
                        }
                    } else {
                        UtilsToast.showToast(Main2Activity_ditu.this,rCode+"" );
                        ToastUtil.showerror(Main2Activity_ditu.this, rCode);
                    }
                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {

                }
            });
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
           // poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true));//
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }

    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:"
                    + cities.get(i).getCityCode() + "城市编码:"
                    + cities.get(i).getAdCode() + "\n";
        }
        UtilsToast.showToast(this, infomation);

    }
//    /**
//     * 点击搜索按钮
//     */
//    public void searchButton() {
//        keyWord = AMapUtil.checkEditText(mEd_sousuo);
//        if ("".equals(keyWord)) {
//        UtilsToast.showToast(this, "请输入关键字");
//            return;
//        } else {
//            doSearchQuery();
//        }
//    }

    /**
     * 点击下一页按钮
     */
    public void nextButton() {
        if (query != null && poiSearch != null && poiResult != null) {
            if (poiResult.getPageCount() - 1 > currentPage) {
                currentPage++;
                query.setPageNum(currentPage);// 设置查后一页
                poiSearch.searchPOIAsyn();
            } else {
                UtilsToast.showToast(this, "没有多余数据了");
            }
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点


            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }
    }

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int routeType, int mode) {
        LatLonPoint startPoint = new LatLonPoint(mLatitude, mLongitude);
        mStartPoint= startPoint;
        mEndPoint =mLatLonPoint;
        if (mStartPoint == null) {
            ToastUtil.show(this, "定位中，稍后再试...");
            return;
        }
        if (mEndPoint == null) {
            ToastUtil.show(this, "终点未设置");
        }
        showProgressDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
        if (routeType == ROUTE_TYPE_DRIVE) {// 驾车路径规划
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, mode, null,
                    null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
        }

    }


    /**
     * 当地图被点击了的回调
     * @param latLng 包含 坐标消息的
     */
    @Override
    public void onMapClick(LatLng latLng) {
        //设定终点 并且 把坐标点传给 工具类 翻译成 具体资料信息
        showCoderSearch(setEndPoint(latLng));

    }

    /**
     * 通过 坐标点 翻译成  具体地方中文的
     */
    private void showCoderSearch(final LatLonPoint mLatLonPoint) {
        geocoderSearch = new GeocodeSearch(this);

        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                RegeocodeAddress regeocodeAddress = result.getRegeocodeAddress();
                String formatAddress = regeocodeAddress.getFormatAddress();
                LogUtils.i("点击位置的数据"+formatAddress);
                if (rCode == 1000) {
                    if (result != null && result.getRegeocodeAddress() != null
                            && result.getRegeocodeAddress().getFormatAddress() != null) {

                        //终点文字信息
                        addressName = result.getRegeocodeAddress().getFormatAddress()
                                + "附近";
                        LogUtils.i("点击地图的点的数据"+addressName);
                        //移动到这个点 设定缩放范围
                        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                                AMapUtil.convertToLatLng(mLatLonPoint), 15));
                        //设定一个号 给这个 覆盖物
                        regeoMarker.setPosition(AMapUtil.convertToLatLng(mLatLonPoint));

                        ed_end.setText(addressName);

                        ToastUtil.show(Main2Activity_ditu.this, addressName);
                    } else {
                        ToastUtil.show(Main2Activity_ditu.this, "没有数据");
                    }
                } else {
                    ToastUtil.showerror(Main2Activity_ditu.this, rCode);
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult result, int rCode) {
            }
        });
        //通过终点 来设定终点 坐标
        RegeocodeQuery query = new RegeocodeQuery(mLatLonPoint, 200,GeocodeSearch.AMAP);
        geocoderSearch.getFromLocationAsyn(query);
    }

    /**
     * 当覆盖物被点击了
     * @param marker
     * @return
     */
    @Override
    public boolean onMarkerClick(Marker marker) {
        //marker.getId()
        String id = marker.getId();
        String snippet = marker.getSnippet();

        LogUtils.i("覆盖物marker"+marker.getTitle());
        LatLng latLng = marker.getPosition();
        LogUtils.i("内容是"+marker.getTitle()+id+snippet);
        UtilsToast.showToast(this, "内容是"+marker.getTitle()+snippet);
        setEndPoint(latLng);

        return true;
    }

    /**
     * 设定终点
     * @param latLng
     */
    private LatLonPoint setEndPoint(LatLng latLng) {
        double latitude = latLng.latitude;
        double longitude = latLng.longitude;
        LogUtils.i("点击的点的经纬度"+"latitude"+latitude+"\n"+"longitude"+longitude);
        mLatLonPoint = new LatLonPoint(latitude, longitude);
        return mLatLonPoint;
    }

    /**
     * 信息窗口被点击了
     * @param marker
     */
    @Override
    public void onInfoWindowClick(Marker marker) {

    }

    /**
     * 返回覆盖物
     * @param marker
     * @return
     */
    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    /**
     * 路线规划相关
     * @param busRouteResult
     * @param i
     */
    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    /**
     * 路线规划结果 (重要)
     * @param result
     * @param errorCode
     */
    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        dissmissProgressDialog();
        // 清理地图上的所有覆盖物
        mAMap.clear();
        if (errorCode == 1000) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    //获取一个结果集
                    mDriveRouteResult = result;
                    //通过结果集获取道路信息 DrivePath
                    final DrivePath drivePath = mDriveRouteResult.getPaths()
                            .get(0);
                    DrivingRouteOverLay drivingRouteOverlay = new DrivingRouteOverLay(
                            this, mAMap, drivePath,
                            mDriveRouteResult.getStartPos(),
                            mDriveRouteResult.getTargetPos(), null);
                    drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                    drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
                   // mBottomLayout.setVisibility(View.VISIBLE);
                    int dis = (int) drivePath.getDistance();
                    int dur = (int) drivePath.getDuration();
                    String des = AMapUtil.getFriendlyTime(dur)+"("+AMapUtil.getFriendlyLength(dis)+")";
                    LogUtils.i("路线规划时间"+des);

                   // mRotueTimeDes.setText(des);
                   // mRouteDetailDes.setVisibility(View.VISIBLE);
                    int taxiCost = (int) mDriveRouteResult.getTaxiCost();
                    LogUtils.i("路线规划打车大约"+taxiCost);

                    LogUtils.i("统计规划路线的数据为"+"\n"+"路线规划时间"+des+"\n"+"路线规划打车大约"+taxiCost+"\n");
                    UtilsToast.showToast(this,"统计规划路线的数据为"+"\n"+"路线规划时间"+des+"\n"+"路线规划费用大约是"+taxiCost+"\n" );
                    //   mRouteDetailDes.setText("打车约"+taxiCost+"元");
                  //  mBottomLayout.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            Intent intent = new Intent(mContext,
//                                    DriveRouteDetailActivity.class);
//                            intent.putExtra("drive_path", drivePath);
//                            intent.putExtra("drive_result",
//                                    mDriveRouteResult);
//                            startActivity(intent);
//                        }
//                    });
                } else if (result != null && result.getPaths() == null) {
                    ToastUtil.show(this, "没收到相关数据");
                }

            } else {
                ToastUtil.show(this, "没收到相关数据");
            }
        } else {
            ToastUtil.showerror(this.getApplicationContext(), errorCode);
        }
    }

    /**
     * 路线规划相关
     * @param walkRouteResult
     * @param i
     */
    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    /**
     * 路线规划相关
     * @param rideRouteResult
     * @param i
     */
    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }



    /**
     * TextWatcher 这个接口里面的内容
     * @param charSequence
     * @param i
     * @param i1
     * @param i2
     */
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    /**
     * TextWatcher 这个接口里面的内容
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //RouteTask.getInstance(getApplicationContext()).setStartPoint(new PositionEntity(mLongitude,mLatitude,"哈尔滨","哈尔滨"));
        //RouteTask.getInstance(getApplicationContext()).setEndPoint(new PositionEntity(mLongitude,mLatitude,"哈尔滨","哈尔滨"));
//        if(RouteTask.getInstance(getApplicationContext()).getStartPoint()==null){
//            Toast.makeText(getApplicationContext(), "检查网络，Key等问题", Toast.LENGTH_SHORT).show();
//            return;
//        }

//        InputTipTask.getInstance(getApplicationContext(), mRecomandAdapter).searchTips(s.toString(),
//                RouteTask.getInstance(getApplicationContext()).getStartPoint().city);
        if (s.length()==0){
            mRecommendList.setVisibility(View.GONE);
            return;
        }
        doSearchQuery( s.toString(),"","230100");
        if (null!=mPoiItems){
            ArrayList<PositionEntity> positionEntities = new ArrayList<>();
            LogUtils.i("范围变化的"+mPoiItems);
            for (int i = 0; i < mPoiItems.size(); i++) {
                PoiItem poiItem = mPoiItems.get(i);
                //String adName = poiItem.getAdName();
                String adName= poiItem.getDirection();
                LatLonPoint latLonPoint = poiItem.getLatLonPoint();
                double longitude = latLonPoint.getLongitude();
                double latitude = latLonPoint.getLatitude();
                PositionEntity positionEntity = new PositionEntity(latitude, longitude, poiItem.toString(), "0451");
                positionEntities.add(positionEntity);
            }
           // mRecomandAdapter.setData(positionEntities);
          //  mRecommendList.setVisibility(View.VISIBLE);
        }



//        List<PositionEntity> positionEntities = mRecomandAdapter.getPositionEntities();
//        LogUtils.i("文本改变了"+positionEntities.toString());
//        PoiSearchTask poiSearchTask=new PoiSearchTask(getApplicationContext(),
//                mRecomandAdapter);//生成poiSearchTask对象


    }

    /**
     * TextWatcher 这个接口里面的内容
     * @param editable
     */
    @Override
    public void afterTextChanged(Editable editable) {

    }

    /**
     * 点击搜索框 集合条目之后发生的事情
     * @param adapterView
     * @param view
     * @param position
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        PositionEntity entity = (PositionEntity) mRecomandAdapter.getItem(position);
        if (entity.latitue == 0 && entity.longitude == 0) {
            PoiSearchTask poiSearchTask=new PoiSearchTask(getApplicationContext(), mRecomandAdapter);
            poiSearchTask.search(entity.address,RouteTask.getInstance(getApplicationContext()).getStartPoint().city);

        } else {
            mRouteTask.setEndPoint(entity);
            mRouteTask.search();
            mRecommendList.setVisibility(View.GONE);
//            Intent intent = new Intent(DestinationActivity1.this, MainActivity1.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//            startActivity(intent);
//            finish();
        }
    }

    @Override
    public void onLocationGet(PositionEntity entity) {
        // todo 这里在网络定位时可以减少一个逆地理编码
        mEd_sousuo.setText(entity.address);
        RouteTask.getInstance(getApplicationContext()).setStartPoint(entity);

        mStartPosition = new LatLng(entity.latitue, entity.longitude);
        CameraUpdate cameraUpate = CameraUpdateFactory.newLatLngZoom(
                mStartPosition, mAMap.getCameraPosition().zoom);
        mAMap.animateCamera(cameraUpate);

    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {
        mEd_sousuo.setText(entity.address);
        mEd_sousuo.setSelection(mEd_sousuo.length());
        entity.latitue = mStartPosition.latitude;
        entity.longitude = mStartPosition.longitude;
        RouteTask.getInstance(getApplicationContext()).setStartPoint(entity);
        RouteTask.getInstance(getApplicationContext()).search();
    }

            @Override
            public void onRouteCalculate(float cost, float distance, int duration) {
//                mDestinationContainer.setVisibility(View.VISIBLE);
//                mIsRouteSuccess = true;
//                mRouteCostText.setVisibility(View.VISIBLE);
                mEd_sousuo.setText(RouteTask
                        .getInstance(getApplicationContext()).getEndPoint().address);
                mEd_sousuo.setSelection(mEd_sousuo.length());
//                mRouteCostText.setText(String.format("预估费用%.2f元，距离%.1fkm,用时%d分", cost,
//                        distance, duration));
//                mDestinationButton.setText("我要用车");
//                mCancelButton.setVisibility(View.VISIBLE);
//                mDestinationButton.setOnClickListener(null);
            }
        }
